#####################################################################
# Product:      KnowledgeEngine (Plone Edition)
#
# File:         SubmitButton.py
#
# Copyright:    Copyright (c) 2004, Faulkner Technologies
#
# Author:       Brian Oliver
#
# Description:  This file defines the SubmitButton class, a simple
#               Button for placement in Toolbars
#
# See Also:     Element, Toolbar
#####################################################################

#####################################################################
## Knowledge Engine Library Imports
from Products.KnowledgeEngine.Common import *
from Products.KnowledgeEngine.Core import *
from Products.KnowledgeEngine.Elements.Toolbar.ToolbarTool import ToolbarTool, ToolbarToolInfo
from Products.KnowledgeEngine.PropertyDefinition import PropertyDefinition
from Products.KnowledgeEngine.PropertyFormats import *
from Products.KnowledgeEngine.PropertyTypes import *
from Products.KnowledgeEngine.PropertyDefinition import *
from Products.KnowledgeEngine.PropertyTypes import *
from Products.KnowledgeEngine.PropertyFormats import *
from Products.KnowledgeEngine.PropertyStructures import *

#####################################################################
## Zope Library Imports
from Globals import DTMLFile
from App.ImageFile import ImageFile

#####################################################################
## Python Library Imports
# (none)

#####################################################################
## Private Functions (global)

def getPages(context):
    """
        Returns a [(name,identity)] of pages within the specified
        context (model).
    """

    #get our model
    model = context.getParentByInstanceOf("Model")
    
    #return the list of available pages in the model
    return [(page.getTitleOrId(),page.getIdentity()) for page in model.getPages()]

#####################################################################
## SubmitButtonInfo Class Definition
class SubmitButtonInfo(ToolbarToolInfo):
    """
        Defines the class info methods, defining information about
        the class without needing an instance of the class
    """
    
    #---------------------------------------------------------------#
    
    def getClassName(self):
        """
            Returns the name of the class for which 
            we are providing information.
        """
        return "SubmitButton"

    #---------------------------------------------------------------#

    def getDisplayName(self):
        """
            Return a friendly name for the class instances
            (this is used for displaying in lists etc)
        """
    
        return "Submit Button"
        
    #---------------------------------------------------------------#

    def getIdentityType(self):
        """
            Return the identity type.  
        """
        
        return "toolSubmit"
        
    #---------------------------------------------------------------#
    
    def getClassIcon(self):
        """
            Return the appropriate icon file for the class.
        """
        
        return ImageFile('skins/SubmitButton_icon.png', globals())
        
    #---------------------------------------------------------------#

    def isPermittedInContainer(self, containerClassInfo, containerInstance = None, instance=None):
        """
            ABSTRACT: Returns if class instances (instance) is permitted in 
            the specified container (containerInstance)
            
            NOTE: This is from this class' instance perspective.
        """
        
        #DEFAULT RULE: SubmitButtons are only permitted in Toolbars
        return containerClassInfo.isInstanceOf('Toolbar') and ((containerInstance == None) or (containerInstance != None and len(containerInstance.getChildrenByInstanceOf(self.getClassName())) == 0))
    
    #---------------------------------------------------------------#

    def onConfigureProperties(self):
        """
            Automatically called by the Knowledge Engine once
            the class has been loaded.  Use this method to register 
            class specific properties using the PropertyReflection interface.
            
            If this class is sub-classed, a call must be made to
            the super-class to ensure super-class properties are
            correctly registered
            
            NOTE: This method is called before ClassInfo.onAfterStartup()            
        """

        #initialise the super-class properties for reflection
        ToolbarToolInfo.onConfigureProperties(self)

        #set the default title
        self.getPropertyDefinition('title').setDefaultValue('Submit')

        #set the default id
        self.getPropertyDefinition('id').setDefaultValue('btnSubmit')
      
        #add the 'redirectURL' property        
        self.addPropertyDefinition(PropertyDefinition(identity="redirectURL", displayName="Post Submit Destination URL", description="The URL the client browser will be directed to after the submit has been completed.  Leave blank for the default (myknowledge) area", propertyType=pt_STRING, propertyFormat=pf_TEXT_SINGLELINE, defaultValue=""))
        
        #add the 'displayOn' property
        #(the property represents a sections on which the button is displayed)
        self.addPropertyDefinition(PropertyDefinition(identity="displayOn", displayName="Display On...", description="The pages on which this button will be displayed", defaultValue=[], propertyType=pt_STRING, propertyFormat=pf_NATIVE, propertyStructure=ps_LIST, hasEnumeratedValues=true, enumeratedValuesFunction=getPages))

    #---------------------------------------------------------------#

#####################################################################
## SubmitButton Class Definition
class SubmitButton(ToolbarTool):
    """
        A class to represent a button in a toolbar
    """

    #---------------------------------------------------------------#

    #ABSTRACT TRANSIENT: a ClassInfo implementation instance to provide info about this class
    _CLASSINFO = SubmitButtonInfo()

    #---------------------------------------------------------------#

    def __init__(self, id, identity):
        "Constructor for the SubmitButton"        

        ToolbarTool.__init__(self, id, identity)
        
        #store the redirect URL
        self.redirectURL = ""
        
        #perform onAfterInstanciation processing
        self.onAfterInstanciation()

    #---------------------------------------------------------------#

    def onAfterInstanciation(self):
        """
            Handle Knowledge Engine specific actions after this object 
            has been loaded into memory.  
            
            This is useful for performing backwards compatibility
        """        
        
        #perform default processing
        ToolbarTool.onAfterInstanciation(self)
        
    #---------------------------------------------------------------#

    def getRedirectURL(self):
        """
            Return the URL to redirect to after saving. An empty 
            string means no redirection is necessary.
        """
        
        return self.redirectURL
        
    #---------------------------------------------------------------#

    def setRedirectURL(self, redirectURL):
        """
            Set the URL to redirect to after saving. An empty 
            string means no redirection is necessary.
        """
        
        self.redirectURL = redirectURL
        
    #---------------------------------------------------------------#

    def hasRedirectURL(self):
        """
            Return if the a redirection to another URL occur
            after saving.
        """
        
        return self.getRedirectURL() != ""
        
    #---------------------------------------------------------------#

    def isPreviewPermitted(self):
        """
            Return if the Element is allowed to be previewed.
            
            By default all elements can't be previewed, some however
            should can be previewed. eg: HTMLHeaderFooters
        """
        
        return true
        
    #---------------------------------------------------------------#

    def getContent(self, contentZone, forGenericObject = None, componentContext = None, assessment = None):
        """
            Return the Element generated 
            content for the specified contentZone (a string).   

            This method is called by the Model.index_html dtml file
            to customise the appearance of the output.
            
            By overriding this method, Elements have the opportunity
            to perform customization of the output from a Model
            during the assessment process.
        """
        
        #the result
        result = ""

        if contentZone == "TOOLBAR_TOP" or contentZone == "TOOLBAR_BOTTOM":
            
            #get the page we are currently in (the forGenericObject)            
            lPage = forGenericObject

            #output the button
            if contentZone == "TOOLBAR_TOP":
                prefix = "Top"
            else:
                prefix = "Bottom"

            #should the submit button be displayed on the current page (forGenericObject)
            if lPage is not None:
                if hasattr(self, "displayOn") and lPage.getIdentity() in self.displayOn:

                    #do we have a redirect url?
                    if self.hasRedirectURL():
                        lRedirectURL = self.getRedirectURL()
                    else:
                        lRedirectURL = ""

                    #output the button markup                        
                    result += '<input type="button" id="btn%sSubmit" class="keButton" value="%s" onClick="performAction(%s, %s);">' % (prefix, self.getTitle(), "'submit'", "'" + lRedirectURL + "'")

                else:
                    #do nothing as the lock button is not required
                    pass
                
            else:
                #preview
                result += '<input type="button" id="btn%sSubmit" class="keButton" value="%s">' % (prefix, self.getTitle())
                
        return result
        
    #---------------------------------------------------------------#

#####################################################################
## Class Initialisation

# Register Class Information with the Knowledge Engine
registerGenericObjectClass(SubmitButton)

#####################################################################
